<template>
	<view class="content">


		<z-paging ref="paging" bgColor="#1F2630" @query="getList" v-model="list" :hide-empty-view="true">
			<!--  -->
			<view class="" slot="top">
				<!-- #ifdef APP -->
				<NavBarCommon></NavBarCommon>
				<!-- #endif -->
				<view class="claimBox">
					<image style="position: absolute;left: 2%;" src="@/static/home/right.png" class="claim1" @click="goBack" />
					<view class="claim2">{{ $t('Blindboxairdrop') }}</view>
				</view>
			</view>
			<!--  -->
			<u-gap></u-gap>
			<view class="rounded-lg " style="background-color: #404752;margin: 0 auto;width: 690rpx;">
				<!-- bg1 -->
				<view class="rounded-lg" style="background-color: #1F4FFF;">
					<view class="rounded-lg text-xl text-white text-center p-sm text-bold"
						style="background: linear-gradient(90deg, rgba(251, 213, 147, 1) 0%, rgba(204, 204, 204, 0) 100%);">
						{{ $t('thefirstphase') }}
					</view>
					<u-gap></u-gap>
					<view class="flex">
						<view class="" style="margin-right: 54rpx;margin-left: 40rpx;">
							<image class="" src="/static/webview/bg1.png" style="width: 295rpx;height: 248rpx;">
							</image>
						</view>
						<view class="flex flex-column">
							<view class="text-white" style="font-size: 14px;">
								<view class="">
									{{ $t('Instructionsandrequirements') }}:
								</view>
								<view class="">
									{{ $t('Youcanonlyreceivetheairdropaftercompletingthefirstphaseofthemission') }}
								</view>
							</view>
							<view class="btn text-center rounded-lg p-xs" :class="model.address ? 'noactive' : 'active'"
								@click="receiveHandle"
								style="font-weight: bold;color: #000;width: 201rpx;height: 49rpx;margin-top: 56rpx;">
								{{ $t('completedimmediately') }}
							</view>
						</view>
					</view>
					<u-gap></u-gap>

				</view>
				<u-gap></u-gap>
				<!-- bg2 -->
				<view class="rounded-lg" style="background-color: #1F4FFF;">
					<view class="rounded-lg text-xl text-white text-center p-sm text-bold"
						style="background: linear-gradient(90deg, rgba(251, 213, 147, 1) 0%, rgba(204, 204, 204, 0) 100%);">
						{{ $t('thesecondphase') }}
					</view>
					<u-gap></u-gap>
					<view class="flex" style="">
						<view class="" style="margin-right: 54rpx;margin-left: 40rpx;">
							<image class="" src="/static/webview/bg2.png" style="width: 295rpx;height: 248rpx;">
							</image>
						</view>
						<view class="flex flex-column">
							<view class="text-white" style="font-size: 14px;">
								<view class="">
									{{ $t('Instructionsandrequirements') }}:
								</view>
								<view class="">
									{{ $t('Aftercompleting') }}
								</view>
							</view>
<!-- 							<view class="btn text-center rounded-lg p-xs" :class="model.address ? 'active' : 'noactive'"
								@click="complateHandle"
								style="font-weight: bold;color: #000;width: 201rpx;height: 49rpx;margin-top: 26rpx;">
								{{ $t('Getitnow') }}
							</view> -->
							<u-gap height="10"></u-gap>
							<button  
							:disabled="isButtonDisabled" :loading='isButtonDisabled'
							class="btn text-center rounded-lg p-xs" :class="model.address ? 'active' : 'noactive'"
								@click="complateHandle"
								style="font-weight: bold;color: #000;width: 100px;line-height: 24px;padding: 4px;margin: 0;"
							>
								{{ $t('Getitnow') }}
							</button>
							
						</view>
					</view>
					<u-gap></u-gap>
				</view>
				<u-gap height="70"></u-gap>
				<!-- list -->
				<view class="text-center rounded-lg " style="background-color: #fff;">
					<u-gap height="15"></u-gap>
					<view class="text-md text-bold">
						{{ $t('Collectionrecord') }}
					</view>
					<u-gap height="15"></u-gap>
					<view class="nav flex">
						<view class="flex-1">{{ $t('walletaddress') }}</view>
						<view class="flex-1">{{ $t('Airdropamount') }}</view>
						<view class="flex-1">{{ $t('transactionhash') }}</view>
						<view class="flex-1">{{ $t('CollectionTime') }}</view>
					</view>
					<view class="item flex text-sm" v-for="(item, index) in list" :key="index">
						<view class="flex-1" style="height: 66rpx;line-height: 66rpx;">{{ formatPublicKey(item.address) }}</view>
						<view class="flex-1" style="height: 66rpx;line-height: 66rpx;">{{ Number(item.amountClaimed).toFixed(2) }}
						</view>
						<view class="flex-1" style="height: 66rpx;line-height: 66rpx;">{{ formatPublicKey(item.hx) }}</view>
						<view class="flex-1" style="height: 66rpx;line-height: 66rpx;">{{ timeFmate(item.claimedAt) }}</view>
					</view>
					<view class="flex">
						<view class="flex-1 mt-md" v-if="list.length == 0">---</view>
						<view class="flex-1 mt-md" v-if="list.length == 0">---</view>
						<view class="flex-1 mt-md" v-if="list.length == 0">---</view>
						<view class="flex-1 mt-md" v-if="list.length == 0">---</view>
					</view>
					<u-gap height="15"></u-gap>
				</view>
			</view>
			<u-gap></u-gap>
			<u-gap></u-gap>
			<!--  -->

			<view class="" slot="bottom">

			</view>
		</z-paging>
	</view>
</template>

<script>
import { airdroprewards, airdropinfo, airdroptransaction, getStagesInfo } from '@/api/index.js'
import { Connection, Transaction, SystemProgram, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js'

/*  */
import env from '@/utils/env.js'
const NETWORK_URL = env.rpcURL
const connection = new Connection(NETWORK_URL);
export default {
	data() {
		return {
			isButtonDisabled:false,
			list: [],
			current_stage_number: 1,
			airdrop: 'https://giveaway.com/zh-CN/aU1kD97dVkP',
			signature: "",
			randomNumber: "",
			model: {
				"id": 0,
				"address": "",
				"amountClaimed": "",
				"claimedAt": "",
				"hx": '',
				"status": "",
				"created_at": ""
			},
			isReceive: false
		};
	},
	methods: {

		async getStagesInfoApi() {
			let res = await getStagesInfo()
			console.log(res, 'res');
			if (res.code == 200) {
				this.airdrop = res.data.airdrop
			}


		},
		formatPublicKey(key) {
			if (!key) return "";
			const start = key.slice(0, 4);
			const end = key.slice(-4);
			return `${start}...${end}`;
		},


		/* 点击完成 */
		complateHandle() {
			console.log('complateHandle 2222');
			/* */
			/* 
			claimedAt
			hx
			*/
			console.log(Boolean(this.model.claimedAt), 'at');
			console.log(Boolean(this.model.hx), 'hx');
			// if (!Boolean(this.model.claimedAt)&& !Boolean(this.model.hx)) {

			if (Array.isArray(this.model)) {
				uni.showToast({
					title: '没有领取资格',
					icon: 'none'
				})
			} else if (typeof this.model === "object" && this.model !== null && this.model.hx == null) {
				console.log('已经完成 可以领取');
				console.log('构建交易');
				uni.$u.debounce(this.airdroptransactionApi, 500)
				// this.airdroptransactionApi()
			} else {
				uni.showToast({
					title: "已经领取过了",
					icon: "none"
				})
			}

		},
		/* 点击领取 */
		receiveHandle() {
			console.log('receiveHandle');
			console.log(this.model, 'this.model');

			if (this.isReceive) {
				console.log('已经完成 不要跳转');
				uni.showToast({
					title: "已完成任务",
					icon: "none"
				})
			} else {
				console.log('未完成 要跳转');
				// uni.navigateTo({
				// 	url: '/pages/h5url/h5url',
				// })
				let url = this.airdrop;
				try {
					// window.location.replace(decodeURIComponent(url))
					window.location.href = url
				} catch (error) {
					window.location = decodeURIComponent(url)
				}
			}
		},
		// 保存空投记录
		async airdroprewards() {
			let data = {
				"address": uni.getStorageSync('walletAddress'),
				"cxc": this.randomNumber,
				"hx": this.signature
			}
			let res = await airdroprewards(data)
			if (res.code == 200) {
				this.isButtonDisabled = false
				uni.showToast({
					title: "领取成功",
					icon: "none"
				})
				this.airdropinfoApi()
			}
		},
		// 构建空投交易
		async airdroptransactionApi() {
			this.isButtonDisabled = true
			let data = {
				"address": uni.getStorageSync('walletAddress'),
			}
			let res = await airdroptransaction(data)
			if (res.code == 200) {
				/* 交换nasy金额 */
				this.randomNumber = res.data.randomNumber
				let serializedTransaction = res.data.serializedTransaction.data
				if (serializedTransaction) {
					console.log('发送广播');
					const txBuffer = new Uint8Array(serializedTransaction);
					const transaction = Transaction.from(txBuffer);
					// const { signature } = await window.solana.signAndSendTransaction(transaction);
					let signature = ''
					let signAndSendTransaction = {
						signature:''
					}
					try{
						 signAndSendTransaction = await window.solana.signAndSendTransaction(transaction);
					}catch(e){
						console.log('e',e);
						this.isButtonDisabled = false
						uni.showToast({
							title: '拒绝交易',
							icon: "error"
						})
						return;
					}
					signature =  signAndSendTransaction.signature
					console.log("交易签名:", signature);
					// 等待确认
					try {
						const confirmation = await connection.confirmTransaction(signature, 'confirmed')
						if (confirmation.value.err) {
							console.log('交易确认失败');
							uni.showToast({
								title: '交易不合法',
								icon: "error"
							})
							this.isButtonDisabled = false
							throw new Error('交易确认失败')
							return;
						}
						if (signature) {
							console.log('signature 交易存在', signature);
							this.signature = signature
							/* 保存记录 */
							this.airdroprewards()
						}
					} catch (err) {
						uni.showToast({
							title: '网络错误,请更换节点',
							icon: 'none'
						})
						this.isButtonDisabled = false
						console.log('err network', err);
					}
				}
			} else {
				// uni.hideLoading({})
				this.isButtonDisabled = false
				
			}
		},
		// 查询 空投信息
		async airdropinfoApi() {
			let address = uni.getStorageSync('walletAddress')
			let res = await airdropinfo(address)
			if (res.code == 200) {
				if (res.data.length == 1) {
					this.model = res.data[0]
					this.list = res.data
					// console.log(this.model, 'this.model ');
					this.isReceive = true
				} else {
					this.isReceive = false
					this.model = []
					this.list = []
				}
			}
		},
		timeFmate(claimedAt) {
			if (!claimedAt) return ''
			const date = new Date(claimedAt);
			// 获取月、日、小时和分钟
			const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从 0 开始的，所以加 1
			const day = String(date.getDate()).padStart(2, '0');
			const hours = String(date.getHours()).padStart(2, '0');
			const minutes = String(date.getMinutes()).padStart(2, '0');
			// 格式化为 "MM-DD HH:mm"
			const formattedTime = `${month}-${day} ${hours}:${minutes}`;
			return formattedTime
		},
		/* 刷新 */
		getList() {
			this.getStagesInfoApi()
			this.airdropinfoApi()
			this.$refs.paging.complete([]);
		},



		// 方法用于格式化 publicKey 的显示
		formatPublicKey(key) {
			if (!key) return "";
			const start = key.slice(0, 4);
			const end = key.slice(-4);
			return `${start}...${end}`;
		},
		goBack() {
			// this.airdroptransactionApi()
			uni.navigateBack()
		},
	},
	computed: {
		// 通过计算属性返回包含 CSS 变量的样式对象
		customStyles() {
			return {
				'--difference-percentage': `${this.holdRewards.differencePercentage}%` // 设置 CSS 变量
			};
		},
		// 一阶段 50% 二阶段 100%
		customStageStyles() {
			if (this.current_stage_number == 1) {
				return {
					'--stage-percentage': '50%' // 设置 CSS 变量
				};
			} else if (this.current_stage_number == 2) {
				return {
					'--stage-percentage': '100%' // 设置 CSS 变量
				};
			}
		},
	},
	onLoad() {

	},
	onShow() {
	}
};
</script>

<style scoped lang="scss">
.active {
	background-color: #FFEB3B;
}

.noactive {
	background-color: #E5E5E5;
}

.intoBox {
	// width: 580rpx;
	height: 12rpx;
	// background: #59cf6f;
	// background: red;
	// background: linear-gradient(to right, #7EDB6A 50%, #001EAE 50%);
	background: linear-gradient(to right, #FFEB3B var(--stage-percentage), #1F2630 0%);
	border-radius: 4rpx;
	margin: 0 auto;
	position: relative;
}



.headerBox {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.leftBox {
	display: flex;
	align-items: center;
	margin-left: 16rpx;
}

.oneImage {
	width: 129rpx;
	height: 129rpx;
}

.hello {
	font-weight: 800;
	font-size: 36rpx;
	color: #ffffff;
	line-height: 64rpx;
}

.recharge-tag {
	display: flex;
	justify-content: center;
	margin: 0 30rpx;

	.recharge-tag-left {
		text {
			font-family: Source Han Sans CN;
			font-weight: 300;
			font-size: 24rpx;
			color: #FFFFFF;
			line-height: 64rpx;
		}
	}

	.recharge-tag-right {
		text {
			font-family: Source Han Sans CN;
			font-weight: 300;
			font-size: 24rpx;
			color: #FFFFFF;
			line-height: 64rpx;
		}
	}
}

.mev-follow-robot-search-wrap {
	margin: 0 30rpx;
	height: 108rpx;
	background: #29313C;
	border-radius: 30rpx;
	border: 2rpx solid #6C7680;
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0 30rpx;

	.mev-follow-robot-search-wrap-icon {
		margin: 30rpx 20rpx 30rpx 30rpx;
		width: 48rpx;
		height: 48rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.mev-follow-robot-search-wrap-input {
		display: flex;
		align-items: center;

		input {
			color: white;
		}
	}

	.mev-follow-robot-search-wrap-select {
		display: flex;
		align-items: center;

		.mev-follow-robot-search-wrap-select-label {
			font-family: Source Han Sans CN;
			font-weight: bold;
			font-size: 24rpx;
			color: #fff;
			// color: #45E5AF;
			line-height: 64rpx;
		}

		.mev-follow-robot-search-wrap-select-icon {
			width: 20rpx;
			height: 12rpx;
			margin-left: 16rpx;
			margin-right: 36rpx;
		}
	}
}

.recharge-header {
	display: flex;
	// align-items: center;
	// justify-content: space-between;
	margin: 0 30rpx;
	justify-content: space-between;



	.recharge-header-back-icon {
		margin-right: 26rpx;

		image {
			width: 22rpx;
			height: 38rpx;
		}
	}

	.recharge-header-title {
		text {
			font-family: Source Han Sans CN;
			font-weight: bold;
			font-size: 36rpx;
			color: #FFFFFF;
			line-height: 36rpx;

		}
	}

	.recharge-header-subtitle {
		// vertical-align: bottom;
		display: flex;
		align-items: end;

		/* 使元素垂直居中 */
		text {
			font-family: Source Han Sans CN;
			font-weight: 300;
			font-size: 24rpx;
			color: #45E5AF;
			// line-height: 64rpx;
		}
	}

}




/*  */
.wallet-avatar-gap {
	border-radius: 40rpx;
	background-color: #4a90e2;
	width: 80rpx;
	height: 80rpx;
	margin-right: 31rpx;
}

.content {
	width: 100%;
	min-height: 100vh;
	background-color: #1f2630;
}

.claimBox {
	display: flex;
	align-items: center;
	justify-content: center;
	padding-top: 50rpx;

	.claim1 {
		width: 22rpx;
		height: 38rpx;
		// margin-left: 28rpx;
	}

	.claim2 {
		font-weight: 500;
		font-size: 36rpx;
		color: #ffffff;
		// margin-left: 195rpx;
	}
}

.addressOne {
	display: flex;
	align-items: center;
	margin-top: 59rpx;
	margin-left: 30rpx;

	.tp {
		width: 100rpx;
		height: 100rpx;
	}

	.address {
		font-weight: 300;
		font-size: 36rpx;
		color: #ffffff;
		margin-left: 21rpx;
	}

	.down {
		width: 25rpx;
		height: 14rpx;
		margin-left: 20rpx;
	}
}

.picBox {
	width: 690rpx;
	height: 420rpx;

	// background-image: url("/static/home/nine.png");
	background: url('/static/home/nine.png') no-repeat;

	background-size: 100%;

	margin-left: 30rpx;
	margin-right: 30rpx;
	margin-top: 30rpx;

	.picOne {
		display: flex;
		align-items: center;
		padding-top: 30rpx;

		.pic1 {
			width: 44rpx;
			height: 48rpx;
			margin-left: 22rpx;
		}

		.num1 {
			font-size: 30rpx;
			color: #ffffff;
			margin-left: 11rpx;
		}

		.num2 {
			font-size: 48rpx;
			color: #ffffff;
			margin-left: 45rpx;
		}

		.pic2 {
			width: 35rpx;
			height: 23rpx;
			margin-left: 20rpx;
		}
	}

	.drawDownBox {
		display: flex;
		align-items: center;
		justify-content: space-around;
		margin-top: 63rpx;

		.drawOne {
			// margin-left: 46rpx;
			text-align: center;

			.one {
				font-size: 36rpx;
				color: #ffffff;
			}

			.one1 {
				font-size: 24rpx;
				color: #8e8e8f;
			}
		}

		.drawTwo {
			// margin-left: 125rpx;
			text-align: center;

			.two {
				font-size: 36rpx;
				color: #ffffff;
			}

			.two2 {
				font-size: 24rpx;
				color: #8e8e8f;
			}
		}

		.drawThree {
			// margin-left: 134rpx;
			text-align: center;

			.three {
				font-size: 36rpx;
				color: #ffffff;
			}

			.three3 {
				font-size: 24rpx;
				color: #8e8e8f;
			}
		}
	}
}

.progress-container {
	width: 600rpx;
	display: flex;
	margin: 0 auto;
	align-items: center;
	// background-color: #333;
	border-radius: 10px;
	// overflow: hidden;
	// margin-left: 45rpx;
	// margin-top: 60rpx;
	position: relative;
	flex-direction: column;
}

.progress-bar {
	width: 600rpx;
	height: 20rpx;
	// background-color: #ffcc00;
	border-radius: 12px;

	background: linear-gradient(to right, #ffcc00 var(--difference-percentage), #1F2631 0%);
	/* 黄色 */
	transition: width 0.5s ease-in-out;
}

.percentage {
	// position: absolute;
	// top: 41%;


	// left: 40%;
	// right: 10px;

	font-size: 72rpx;
	color: #fcd434;
}

.submitBox {
	width: 690rpx;
	height: 88rpx;
	background: #29313C;
	border-radius: 44rpx;
	margin-top: 60rpx;
	margin-left: 30rpx;


	.submit {
		font-weight: bold;
		font-size: 36rpx;
		color: #0d081a;
		line-height: 80rpx;
		text-align: center;
	}
}

.active {
	background: #fcd434 !important;
}
</style>